<template>
    <view :data-theme="globPrimary">
        <u-navbar>
            <view class="topic-navbar-collection" @click="changeCollection">
                <u-icon
                    name="star-fill"
                    :color="collected ? '#FF8A52' : '#DCDFE6'"
                    size="40"
                ></u-icon>
            </view>
            <view class="topic-navbar-sheet" @click="$u.debounce(onOpenCard, 500)">
                <u-image
                    width="40"
                    height="40"
                    src="@/pageFound/static/images/exam_sheet_icon.png"
                ></u-image>
            </view>
        </u-navbar>
        <view class="topic-header u-flex" v-if="!$u.test.empty(topicList)">
            <view class="title u-line-1">{{ examTitle }}</view>
            <u-image
                width="28rpx"
                height="32rpx"
                src="@/pageFound/static/images/maker.png"
                class="img"
            ></u-image>
            <view class="conut active">{{ topicIndex + 1 }}</view>
            <view class="conut">/{{ examCount }}</view>
            <view class="answered" v-if="hasAnswered" :style="[{ top: answeredTop }]">
                <u-image
                    width="148rpx"
                    height="148rpx"
                    src="@/pageFound/static/images/sure.png"
                    class="img"
                    v-if="!loading && answerRight"
                ></u-image>
                <u-image
                    width="148rpx"
                    height="148rpx"
                    src="@/pageFound/static/images/wrong.png"
                    class="img"
                    v-if="!loading && !answerRight"
                ></u-image>
            </view>
        </view>

        <view class="topic-body" v-for="item in topicList" :key="item.id">
            <practice-question
                :question="item"
                :value="questionValue(item)"
                @change="handleQuestionChange"
                :disabled="hasAnswered == 1"
            ></practice-question>
            <practice-parsing
                :parsing="item"
                v-if="!loading && hasAnswered == 1"
            ></practice-parsing>
        </view>

        <practice-pagination
            :show-prev-button="topicIndex > 0"
            :show-next-button="topicIndex < examCount - 1"
            :show-confirm-button="topicIndex == examCount - 1 && !hasAnswered"
            @prev="handleTopicPrev"
            @next="handleTopicNext"
            @confirm="handleQuestionAnswer"
        ></practice-pagination>

        <!-- 答题卡 -->
        <practice-card
            v-model="cardVisible"
            :title="examTitle"
            @change="handleTopicChange"
        ></practice-card>

        <edu-empty v-if="!loading && $u.test.empty(topicRulesList)"></edu-empty>
    </view>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import practiceQuestion from '../components/practice-question.vue'
import practiceParsing from '../components/practice-parsing.vue'
import practicePagination from '../components/practice-pagination.vue'
import practiceCard from '../components/practice-card.vue'
export default {
    components: {
        practiceQuestion,
        practiceParsing,
        practicePagination,
        practiceCard,
    },
    data() {
        return {
            loading: false,
            examTitle: '', // 考试标题
            examCount: 0, // 试题总数
            topicList: [],
            cardVisible: false,
            answerRight: 0, // 答案是否正确
        }
    },
    computed: {
        ...mapState({
            topicIndex: (state) => state.examPractice.topicIndex,
            topicRulesList: (state) => state.examPractice.topicList,
        }),
        ...mapGetters({
            globPrimary: 'designSetting/getGlobTheme',
            globPrimaryColor: 'designSetting/getGlobThemeColor',
            globNavbarHeight: 'projectSetting/globNavbarHeight',
            globStatusBarHeight: 'projectSetting/globStatusBarHeight',
            topicId: 'examPractice/getTopicId',
        }),
        // 收藏状态
        collected() {
            const topic = this.topicList.find((item, index) => item.id == this.topicId)
            if (this.$u.test.empty(topic)) return 0
            return topic.collected
        },
        // 已答
        hasAnswered() {
            const topic = this.topicRulesList.find((item, index) => item.topic_id == this.topicId)
            if (this.$u.test.empty(topic)) return 0
            return topic.has_answered
        },
        answeredTop() {
            let top = this.globNavbarHeight + this.globStatusBarHeight + uni.upx2px(16) + 'px'
            return top
        },
    },
    watch: {
        topicRulesList: {
            handler(val, oldVal) {
                const topic = val.find((item, index) => item.topic_id == this.topicId)
                if (!this.$u.test.empty(topic)) {
                    this.answerRight = topic.is_right
                }
            },
            deep: true,
        },
        topicIndex(val) {
            const topic = this.topicRulesList.find((item, index) => item.topic_id == this.topicId)
            if (!this.$u.test.empty(topic)) {
                this.answerRight = topic.is_right
            }
        },
    },
    onLoad(option) {
        this.getPointInfo(option.id, option.count, option.ids)
    },
    methods: {
        // 获取的基础信息
        getPointInfo(id, count, ids) {
            this.$edu.api
                .getPointPrictice({
                    module_id: id,
                    topic_num: count,
                    point_ids: ids,
                })
                .then((res) => {
                    const { data } = res
                    this.examTitle = data.module_title
                    this.examCount = data.topic_num
                    this.$store.commit('examPractice/init', data.rules)
                    if (!this.$u.test.empty(data.rules)) {
                        this.getExamTopic()
                    }
                })
        },
        // 获取试题
        getExamTopic() {
            uni.showLoading({
                title: '加载中...',
            })
            this.loading = true
            return new Promise((resolve) => {
                this.$edu.api
                    .getPointTopic({
                        topic_id: this.topicId,
                    })
                    .then((res) => {
                        const { data } = res
                        this.topicList = data
                        this.changeCorrectAnswer()
                        setTimeout(() => {
                            this.loading = false
                            uni.hideLoading()
                        }, 500)
                        resolve()
                    })
                    .catch((err) => {
                        uni.hideLoading()
                    })
            })
        },
        // 当前值
        questionValue(item) {
            const rules = this.topicRulesList.find((item) => item.topic_id == this.topicId)
            let empty = null
            if (this.$edu.test.inArray(item.question_type, [1, 2])) {
                empty = ''
            } else if (this.$edu.test.inArray(item.question_type, [3, 4, 7])) {
                empty = []
            }
            if (this.$u.test.empty(rules) || this.$u.test.empty(rules.current_answer)) {
                return empty
            } else {
                return rules.current_answer
            }
        },
        // 保存正确的答案
        changeCorrectAnswer() {
            let topic = this.topicList.find((item, index) => item.id == this.topicId)
            let answer = null
            if (this.$edu.test.inArray(topic.question_type, [1, 2])) {
                // 单选/判断
                let option = topic.options.find((item) => item.is_right)
                if (option) {
                    answer = option.id
                }
            } else if (this.$edu.test.inArray(topic.question_type, [3, 4])) {
                // 多选/不定项选择
                let option = topic.options.filter((item) => item.is_right == 1)
                if (!this.$u.test.empty(option)) {
                    answer = option.map((item) => item.id)
                }
            } else if (this.$edu.test.inArray(topic.question_type, [7])) {
                // 完型填空
                let option = topic.topics.map((ele) => {
                    let options = ele.options.find((item) => item.is_right == 1)
                    return options.id
                })
                if (!this.$u.test.empty(option)) {
                    answer = option
                }
            }
            this.$store.commit('examPractice/changeCorrectAnswer', {
                id: this.topicId,
                answer: answer,
            })
        },
        // 打开答题卡
        onOpenCard() {
            this.cardVisible = true
        },
        // 上一题
        handleTopicPrev() {
            if (!this.loading) {
                this.$store.commit('examPractice/prev')
                this.getExamTopic()
            }
        },
        // 下一题
        handleTopicNext() {
            if (!this.loading) {
                if (this.hasAnswered) {
                    this.$store.commit('examPractice/next')
                    this.getExamTopic()
                } else {
                    this.handleQuestionAnswer()
                }
            }
        },
        // 当前题
        handleTopicChange(index) {
            if (!this.loading) {
                this.$store.commit('examPractice/change', index)
                this.getExamTopic()
            }
        },
        // 选择的答案变化时
        handleQuestionChange(e) {
            if (!this.loading) {
                this.$store.commit('examPractice/changeCurrentAnswer', {
                    id: this.topicId,
                    answer: e,
                })
            }
        },
        // 提交单项答案时
        handleQuestionAnswer() {
            if (!this.loading && !this.hasAnswered) {
                const rules = this.topicRulesList.find((item) => item.topic_id == this.topicId)
                const topic = this.topicList.find((item) => item.id == this.topicId)
                let is_right = 0
                if (this.$edu.test.inArray(topic.question_type, [1, 2])) {
                    // 单选
                    if (rules.correct_answer && rules.current_answer) {
                        is_right = rules.current_answer == rules.correct_answer ? 1 : 0
                    }
                } else {
                    // 多选/数组
                    if (rules.correct_answer && rules.current_answer) {
                        if (rules.correct_answer.length == rules.current_answer.length) {
                            let num = rules.correct_answer.every((item) =>
                                rules.current_answer.includes(item)
                            )
                            is_right = num ? 1 : 0
                        } else {
                            is_right = 0
                        }
                    }
                }
                this.$store.commit('examPractice/submitCurrentAnswer', {
                    id: this.topicId,
                    is_right: is_right,
                })
                this.$edu.api.referPricticeTopic({
                    topic_level: 1,
                    topic_id: this.topicId,
                    is_right: is_right,
                })
                if (is_right && this.topicIndex < this.examCount - 1) {
                    this.$store.commit('examPractice/next')
                    this.getExamTopic()
                }
            }
        },
        // 收藏
        changeCollection() {
            if (!this.loading) {
                let status = this.collected == 1 ? 0 : 1
                this.$edu.api
                    .getTopicCollect({
                        topic_id: this.topicId.toString(),
                        status: status,
                    })
                    .then((res) => {
                        this.$u.toast(res.data)
                        let topic = this.topicList.find((item) => item.id == this.topicId)
                        topic.collected = status
                    })
            }
        },
    },
    destroyed() {
        this.$store.commit('examPractice/init')
    },
}
</script>
<style lang="scss">
page {
    background-color: #ffffff;
}
</style>
<style lang="scss" scoped>
.topic-navbar-collection {
    padding: 10px 20rpx;
    margin-left: auto;
}
.topic-navbar-sheet {
    padding: 10rpx 20rpx;
    margin-left: 10rpx;
    margin-right: 10rpx;
}
.topic-header {
    padding: 30rpx;
    position: relative;
    .title {
        max-width: 60%;
        font-size: 32rpx;
        font-weight: bold;
        color: #303133;
    }
    .img {
        margin-left: auto;
        margin-right: 20rpx;
    }
    .count {
        font-size: 26rpx;
        color: #909399;
    }
    .active {
        @include text-color();
    }
    .answered {
        position: fixed;
        right: 8rpx;
        z-index: 99;
    }
}
.topic-body {
    padding: 0 30rpx;
    margin-bottom: 30rpx;
}
</style>
